

<!DOCTYPE html>
<html lang="zh-CN" data-default-color-scheme=dark>



<head>
  <meta charset="UTF-8">
  <link rel="apple-touch-icon" sizes="76x76" href="/my-blog/img/fluid.png">
  <link rel="icon" href="/my-blog/img/fluid.png">
  <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=5.0, shrink-to-fit=no">
  <meta http-equiv="x-ua-compatible" content="ie=edge">
  
  <meta name="theme-color" content="#2f4154">
  <meta name="author" content="木舟">
  <meta name="keywords" content="python Vue Test 测试开发 自动化测试">
  
    <meta name="description" content="异常处理前言每个编程语言中都会有 异常处理机制 这是肯定的，因为只要你写代码，肯定会有bug，也肯定会有使用不规范&#x2F;不正确的地方。 那么，什么是异常？ 异常就是 触发了之后如果不处理， 程序就没办法继续运行下去，乃至程序崩溃 爆出异常的时候，往往携带很多信息输出：报错原因、报错文件、报错行数 所以我们开发者就可以根据异常信息来定位程序出现的问题，并将其处理 如何处理异常想要知道如何处理异常，首先我">
<meta property="og:type" content="article">
<meta property="og:title" content="python异常处理及文件处理">
<meta property="og:url" content="https://walker_kwu.gitee.io/my-blog/2023/03/18/python/base/python%E5%BC%82%E5%B8%B8%E5%A4%84%E7%90%86%E5%8F%8A%E6%96%87%E4%BB%B6%E5%A4%84%E7%90%86/">
<meta property="og:site_name" content="My Blog">
<meta property="og:description" content="异常处理前言每个编程语言中都会有 异常处理机制 这是肯定的，因为只要你写代码，肯定会有bug，也肯定会有使用不规范&#x2F;不正确的地方。 那么，什么是异常？ 异常就是 触发了之后如果不处理， 程序就没办法继续运行下去，乃至程序崩溃 爆出异常的时候，往往携带很多信息输出：报错原因、报错文件、报错行数 所以我们开发者就可以根据异常信息来定位程序出现的问题，并将其处理 如何处理异常想要知道如何处理异常，首先我">
<meta property="og:locale" content="zh_CN">
<meta property="article:published_time" content="2023-03-18T07:36:20.000Z">
<meta property="article:modified_time" content="2023-05-23T10:37:53.266Z">
<meta property="article:author" content="木舟">
<meta property="article:tag" content="测试开发">
<meta property="article:tag" content="Python基础">
<meta name="twitter:card" content="summary_large_image">
  
  
    <meta name="referrer" content="no-referrer-when-downgrade">
  
  
  <title>python异常处理及文件处理 - My Blog</title>

  <link  rel="stylesheet" href="https://lib.baomitu.com/twitter-bootstrap/4.6.1/css/bootstrap.min.css" />



  <link  rel="stylesheet" href="https://lib.baomitu.com/github-markdown-css/4.0.0/github-markdown.min.css" />

  <link  rel="stylesheet" href="https://lib.baomitu.com/hint.css/2.7.0/hint.min.css" />

  <link  rel="stylesheet" href="https://lib.baomitu.com/fancybox/3.5.7/jquery.fancybox.min.css" />



<!-- 主题依赖的图标库，不要自行修改 -->
<!-- Do not modify the link that theme dependent icons -->

<link rel="stylesheet" href="//at.alicdn.com/t/font_1749284_hj8rtnfg7um.css">



<link rel="stylesheet" href="//at.alicdn.com/t/font_1736178_lbnruvf0jn.css">


<link  rel="stylesheet" href="/my-blog/css/main.css" />


  <link id="highlight-css" rel="stylesheet" href="/my-blog/css/highlight.css" />
  
    <link id="highlight-css-dark" rel="stylesheet" href="/my-blog/css/highlight-dark.css" />
  




  <script id="fluid-configs">
    var Fluid = window.Fluid || {};
    Fluid.ctx = Object.assign({}, Fluid.ctx)
    var CONFIG = {"hostname":"walker_kwu.gitee.io","root":"/my-blog/","version":"1.9.2","typing":{"enable":true,"typeSpeed":70,"cursorChar":"_","loop":false,"scope":[]},"anchorjs":{"enable":true,"element":"h1,h2,h3,h4,h5,h6","placement":"left","visible":"hover","icon":""},"progressbar":{"enable":true,"height_px":3,"color":"#29d","options":{"showSpinner":false,"trickleSpeed":100}},"code_language":{"enable":true,"default":"TEXT"},"copy_btn":true,"image_caption":{"enable":true},"image_zoom":{"enable":true,"img_url_replace":["",""]},"toc":{"enable":true,"placement":"left","headingSelector":"h1,h2,h3,h4,h5,h6","collapseDepth":0},"lazyload":{"enable":true,"loading_img":"/img/loading.gif","onlypost":false,"offset_factor":2},"web_analytics":{"enable":false,"follow_dnt":true,"baidu":null,"google":null,"gtag":null,"tencent":{"sid":null,"cid":null},"woyaola":null,"cnzz":null,"leancloud":{"app_id":null,"app_key":null,"server_url":null,"path":"window.location.pathname","ignore_local":false}},"search_path":"/my-blog/local-search.xml"};

    if (CONFIG.web_analytics.follow_dnt) {
      var dntVal = navigator.doNotTrack || window.doNotTrack || navigator.msDoNotTrack;
      Fluid.ctx.dnt = dntVal && (dntVal.startsWith('1') || dntVal.startsWith('yes') || dntVal.startsWith('on'));
    }
  </script>
  <script  src="/my-blog/js/utils.js" ></script>
  <script  src="/my-blog/js/color-schema.js" ></script>
  


  
<meta name="generator" content="Hexo 6.2.0"></head>


<body>
  

  <header>
    

<div class="header-inner" style="height: 70vh;">
  <nav id="navbar" class="navbar fixed-top  navbar-expand-lg navbar-dark scrolling-navbar">
  <div class="container">
    <a class="navbar-brand" href="/my-blog/">
      <strong>木舟</strong>
    </a>

    <button id="navbar-toggler-btn" class="navbar-toggler" type="button" data-toggle="collapse"
            data-target="#navbarSupportedContent"
            aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">
      <div class="animated-icon"><span></span><span></span><span></span></div>
    </button>

    <!-- Collapsible content -->
    <div class="collapse navbar-collapse" id="navbarSupportedContent">
      <ul class="navbar-nav ml-auto text-center">
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/my-blog/">
                <i class="iconfont icon-home-fill"></i>
                首页
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/my-blog/archives/">
                <i class="iconfont icon-archive-fill"></i>
                归档
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/my-blog/categories/">
                <i class="iconfont icon-category-fill"></i>
                分类
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/my-blog/tags/">
                <i class="iconfont icon-tags-fill"></i>
                标签
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/my-blog/about/">
                <i class="iconfont icon-user-fill"></i>
                关于
              </a>
            </li>
          
        
        
          <li class="nav-item" id="search-btn">
            <a class="nav-link" target="_self" href="javascript:;" data-toggle="modal" data-target="#modalSearch" aria-label="Search">
              &nbsp;<i class="iconfont icon-search"></i>&nbsp;
            </a>
          </li>
          
        
        
          <li class="nav-item" id="color-toggle-btn">
            <a class="nav-link" target="_self" href="javascript:;" aria-label="Color Toggle">&nbsp;<i
                class="iconfont icon-dark" id="color-toggle-icon"></i>&nbsp;</a>
          </li>
        
      </ul>
    </div>
  </div>
</nav>

  

<div id="banner" class="banner" parallax=true
     style="background: url('/my-blog/img/default.png') no-repeat center center; background-size: cover;">
  <div class="full-bg-img">
    <div class="mask flex-center" style="background-color: rgba(0, 0, 0, 0.3)">
      <div class="banner-text text-center fade-in-up">
        <div class="h2">
          
            <span id="subtitle" data-typed-text="python异常处理及文件处理"></span>
          
        </div>

        
          
  <div class="mt-3">
    
      <span class="post-meta mr-2">
        <i class="iconfont icon-author" aria-hidden="true"></i>
        木舟
      </span>
    
    
      <span class="post-meta">
        <i class="iconfont icon-date-fill" aria-hidden="true"></i>
        <time datetime="2023-03-18 15:36" pubdate>
          2023年3月18日 下午
        </time>
      </span>
    
  </div>

  <div class="mt-1">
    
      <span class="post-meta mr-2">
        <i class="iconfont icon-chart"></i>
        
          6.6k 字
        
      </span>
    

    

    
    
      
        <span id="busuanzi_container_page_pv" style="display: none">
          <i class="iconfont icon-eye" aria-hidden="true"></i>
          <span id="busuanzi_value_page_pv"></span> 次
        </span>
        
      
    
  </div>


        
      </div>

      
    </div>
  </div>
</div>

</div>

  </header>

  <main>
    
      

<div class="container-fluid nopadding-x">
  <div class="row nomargin-x">
    <div class="side-col d-none d-lg-block col-lg-2">
      
  <aside class="sidebar" style="padding-left: 2rem; margin-right: -1rem">
    <div id="toc">
  <p class="toc-header"><i class="iconfont icon-list"></i>&nbsp;目录</p>
  <div class="toc-body" id="toc-body"></div>
</div>



  </aside>


    </div>

    <div class="col-lg-8 nopadding-x-md">
      <div class="container nopadding-x-md" id="board-ctn">
        <div id="board">
          <article class="post-content mx-auto">
            <!-- SEO header -->
            <h1 style="display: none">python异常处理及文件处理</h1>
            
              <p class="note note-info">
                
                  
                    本文最后更新于：2023年5月23日 晚上
                  
                
              </p>
            
            
              <div class="markdown-body">
                
                <h1 id="异常处理"><a href="#异常处理" class="headerlink" title="异常处理"></a>异常处理</h1><h2 id="前言"><a href="#前言" class="headerlink" title="前言"></a>前言</h2><p>每个编程语言中都会有 <strong>异常处理机制</strong></p>
<p>这是肯定的，因为只要你写代码，肯定会有bug，也肯定会有使用不规范/不正确的地方。</p>
<p>那么，什么是异常？</p>
<p>异常就是 <strong>触发了之后如果不处理， 程序就没办法继续运行下去，乃至程序崩溃</strong></p>
<p>爆出异常的时候，往往携带很多信息输出：报错原因、报错文件、报错行数</p>
<p>所以我们开发者就可以根据异常信息来定位程序出现的问题，并将其处理</p>
<h2 id="如何处理异常"><a href="#如何处理异常" class="headerlink" title="如何处理异常"></a>如何处理异常</h2><p>想要知道如何处理异常，首先我们得知道如何快速引发一个常见的异常</p>
<p>比如： <code>int(&#39;a&#39;)</code></p>
<p>我们字符串在转化成整型的时候，如果转化后的不是一个正常的数字，那么就会报错</p>
<p>所以我们可以直接输入 <code>int(&#39;a&#39;)</code> 然后运行</p>
<p>不出意外，你可以看到如下异常：</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><code class="hljs python">Traceback (most recent call last):<br>  File <span class="hljs-string">&quot;C:\Users\xx\Desktop\python基础\test.py&quot;</span>, line <span class="hljs-number">1</span>, <span class="hljs-keyword">in</span> &lt;module&gt;<br>    <span class="hljs-built_in">int</span>(<span class="hljs-string">&#x27;a&#x27;</span>)<br>ValueError: invalid literal <span class="hljs-keyword">for</span> <span class="hljs-built_in">int</span>() <span class="hljs-keyword">with</span> base <span class="hljs-number">10</span>: <span class="hljs-string">&#x27;a&#x27;</span><br></code></pre></td></tr></table></figure>

<p>那么，我们要如何处理异常呢？</p>
<p>首先我们明确一点，发生异常时，肯定是 <strong>出乎意料的</strong></p>
<p>也就是说，发生异常的代码，有极小的概率是会触发这个异常的，反过来意思就是 <strong>在大部分运行时间内，它是正常的</strong></p>
<p>所以我们要做的是 <strong>当异常发生的时候，我们要捕捉它；当异常没有发生的时候，我们就当作什么都不知道</strong></p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br></pre></td><td class="code"><pre><code class="hljs python"><span class="hljs-keyword">def</span> <span class="hljs-title function_">maybeError</span>(<span class="hljs-params">value</span>):<br><br>    <span class="hljs-keyword">try</span>:<br>        p = <span class="hljs-built_in">int</span>(value)<br>        <span class="hljs-built_in">print</span>(p)<br>    <span class="hljs-keyword">except</span>:<br>        <span class="hljs-built_in">print</span>(<span class="hljs-string">f&quot;哎呀报错啦，你这个值 <span class="hljs-subst">&#123;value&#125;</span> 不太对劲哦&quot;</span>)<br><br><br>maybeError(<span class="hljs-string">&#x27;1&#x27;</span>)<br>maybeError(<span class="hljs-string">&#x27;a&#x27;</span>)<br><br><span class="hljs-comment"># 结果：</span><br><span class="hljs-comment"># 1</span><br><span class="hljs-comment"># 哎呀报错啦，你这个值 a 不太对劲哦</span><br></code></pre></td></tr></table></figure>

<h2 id="异常捕获流程"><a href="#异常捕获流程" class="headerlink" title="异常捕获流程"></a>异常捕获流程</h2><p>上面的 <code>try...except...</code> 只是最基本的捕获手段，我们先来解读一下这两个关键字：</p>
<ul>
<li>try: 尝试运行一段代码，如果没有报错那就是最好</li>
<li>except: 如果try运行的代码报错了，就会触发这个关键字，运行这个关键字对应的代码</li>
</ul>
<p>但 <strong>完整</strong> 的异常关键字还有其他两个</p>
<ul>
<li>try: 尝试运行一段代码，如果没有报错那就是最好</li>
<li>except: 如果try运行的代码报错了，就会触发这个关键字，运行这个关键字对应的代码</li>
<li>else: 如果try运行没问题，就运行else对应的代码</li>
<li>finally：不管try是否运行成功，都会触发这个关键字，运行这个关键字对应的代码</li>
</ul>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br></pre></td><td class="code"><pre><code class="hljs python"><span class="hljs-keyword">def</span> <span class="hljs-title function_">maybeError</span>(<span class="hljs-params">valueList</span>):<br>    oldValueList = []  <span class="hljs-comment"># 这里可以是从数据库搜索出来的旧值</span><br>    <span class="hljs-keyword">try</span>:<br>        newValueList = [<span class="hljs-built_in">int</span>(newValue) <span class="hljs-keyword">for</span> newValue <span class="hljs-keyword">in</span> valueList]<br>    <span class="hljs-keyword">except</span>:<br>        <span class="hljs-built_in">print</span>(<span class="hljs-string">f&quot;哎呀报错啦，你这个列表 <span class="hljs-subst">&#123;valueList&#125;</span> 不太对劲哦&quot;</span>)<br>    <span class="hljs-keyword">else</span>:<br>        <span class="hljs-built_in">print</span>(<span class="hljs-string">&quot;嗯，你这个列表很好很完美，我要清空以前的旧数据，并且把你这个新的存进去&quot;</span>)<br>    <span class="hljs-keyword">finally</span>:<br>        <span class="hljs-built_in">print</span>(<span class="hljs-string">&quot;不管怎么样数据库连接我肯定是要关闭的&quot;</span>)<br><br><span class="hljs-built_in">print</span>(<span class="hljs-string">&quot;first execute:&quot;</span>)<br>maybeError([<span class="hljs-string">&#x27;1&#x27;</span>, <span class="hljs-string">&#x27;2&#x27;</span>, <span class="hljs-string">&#x27;3&#x27;</span>])<br><span class="hljs-built_in">print</span>(<span class="hljs-string">&quot;\nsecond execute:&quot;</span>)<br>maybeError([<span class="hljs-string">&#x27;1&#x27;</span>, <span class="hljs-string">&#x27;a&#x27;</span>, <span class="hljs-string">&#x27;3&#x27;</span>])<br><br><span class="hljs-comment"># 结果</span><br><span class="hljs-string">&quot;&quot;&quot;</span><br><span class="hljs-string">first execute:</span><br><span class="hljs-string">嗯，你这个列表很好很完美，我要清空以前的旧数据，并且把你这个新的存进去</span><br><span class="hljs-string">不管怎么样数据库连接我肯定是要关闭的</span><br><span class="hljs-string"></span><br><span class="hljs-string">second execute:</span><br><span class="hljs-string">哎呀报错啦，你这个列表 [&#x27;1&#x27;, &#x27;a&#x27;, &#x27;3&#x27;] 不太对劲哦</span><br><span class="hljs-string">不管怎么样数据库连接我肯定是要关闭的</span><br><span class="hljs-string">&quot;&quot;&quot;</span><br></code></pre></td></tr></table></figure>

<p>当我们使用 异常捕获时，<code>try</code>是必须要写的，<code>except/finally</code>至少要写一个，<code>else</code>不做要求</p>
<p>所以，如何利用异常处理机制，要根据实际情况而定。</p>
<h2 id="异常指定捕获"><a href="#异常指定捕获" class="headerlink" title="异常指定捕获"></a>异常指定捕获</h2><p>从上述例子我们可以看到，<code>except</code> 是不管 <code>try</code>的代码发生什么异常，都会触发这个关键字</p>
<p>但是我们更多的时候，只要捕获 <strong>特定的异常</strong></p>
<p>这是为什么？因为我们要让程序变得更加可控。</p>
<p>打个比方，你使用 <code>except</code> 捕获到了一种异常，并将其处理。</p>
<p>但是在未来的某一天，你的程序又发生了另一种异常，但是由于你使用了 <code>except</code>，你会将这另一种异常当作之前的异常来看待</p>
<p>但实际上它们两造成的影响/结果都有可能大大的不同。</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br></pre></td><td class="code"><pre><code class="hljs python"><span class="hljs-keyword">def</span> <span class="hljs-title function_">maybeError</span>(<span class="hljs-params">valueDict</span>):<br>    <span class="hljs-keyword">try</span>:<br>        <span class="hljs-built_in">print</span>(<span class="hljs-string">f&quot;你传入的字典没有问题，岁数：<span class="hljs-subst">&#123;<span class="hljs-built_in">int</span>(valueDict[<span class="hljs-string">&#x27;age&#x27;</span>])&#125;</span>&quot;</span>)<br>    <span class="hljs-keyword">except</span>:<br>        <span class="hljs-built_in">print</span>(<span class="hljs-string">f&quot;你传入的字典中的岁数不太对啊，不是个正常的字符串数字 <span class="hljs-subst">&#123;valueDict&#125;</span>&quot;</span>)<br>    <br><br><span class="hljs-built_in">print</span>(<span class="hljs-string">&quot;first execute:&quot;</span>)<br>maybeError(&#123;<span class="hljs-string">&#x27;age&#x27;</span>: <span class="hljs-string">&#x27;1b&#x27;</span>&#125;)<br><span class="hljs-built_in">print</span>(<span class="hljs-string">&quot;\nsecond execute:&quot;</span>)<br>maybeError(&#123;&#125;)<br><br><span class="hljs-comment"># 结果</span><br><span class="hljs-string">&quot;&quot;&quot;</span><br><span class="hljs-string">first execute:</span><br><span class="hljs-string">你传入的字典中的岁数不太对啊，不是个正常的字符串数字 &#123;&#x27;age&#x27;: &#x27;1b&#x27;&#125;</span><br><span class="hljs-string"></span><br><span class="hljs-string">second execute:</span><br><span class="hljs-string">你传入的字典中的岁数不太对啊，不是个正常的字符串数字 &#123;&#125;</span><br><span class="hljs-string">&quot;&quot;&quot;</span><br></code></pre></td></tr></table></figure>

<p>可以发现，对于第一次执行，这样的提示文字是没有问题的，也可以帮助开发者去定位问题或者给使用者一个很好的反馈</p>
<p>但是第二次执行，这样的提示文字显然和实际情况很不相符。</p>
<p>所以我们需要进行指定捕获：</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br></pre></td><td class="code"><pre><code class="hljs python"><span class="hljs-keyword">def</span> <span class="hljs-title function_">maybeError</span>(<span class="hljs-params">valueDict</span>):<br>    <span class="hljs-keyword">try</span>:<br>        <span class="hljs-built_in">print</span>(<span class="hljs-string">f&quot;你传入的字典没有问题，岁数：<span class="hljs-subst">&#123;<span class="hljs-built_in">int</span>(valueDict[<span class="hljs-string">&#x27;age&#x27;</span>])&#125;</span>&quot;</span>)<br>    <span class="hljs-keyword">except</span> ValueError:<br>        <span class="hljs-built_in">print</span>(<span class="hljs-string">f&quot;你传入的字典中的岁数不太对啊，不是个正常的字符串数字 <span class="hljs-subst">&#123;valueDict&#125;</span>&quot;</span>)<br>    <span class="hljs-keyword">except</span> KeyError:<br>        <span class="hljs-built_in">print</span>(<span class="hljs-string">f&quot;你传入的字典中没有 岁数 字段 <span class="hljs-subst">&#123;valueDict&#125;</span>&quot;</span>)<br>    <span class="hljs-keyword">except</span>:<br>        <span class="hljs-built_in">print</span>(<span class="hljs-string">f&quot;程序发生了未知异常&quot;</span>)<br>    <br><br><span class="hljs-built_in">print</span>(<span class="hljs-string">&quot;first execute:&quot;</span>)<br>maybeError(&#123;<span class="hljs-string">&#x27;age&#x27;</span>: <span class="hljs-string">&#x27;1b&#x27;</span>&#125;)<br><span class="hljs-built_in">print</span>(<span class="hljs-string">&quot;\nsecond execute:&quot;</span>)<br>maybeError(&#123;&#125;)<br></code></pre></td></tr></table></figure>

<p><strong>异常捕获</strong> 也是多分支的，和 <code>if...elif...</code> 一样，由上到下，捕获到一种异常后，即不会运行以下的 <code>except</code>。</p>
<p>想想也是，同一时间肯定只有一种异常会触发。</p>
<h2 id="查看异常信息"><a href="#查看异常信息" class="headerlink" title="查看异常信息"></a>查看异常信息</h2><p>我们上面的做法，只是针对某些异常做出处理，但是更多的时候，我们使用 <code>try</code> 是为了定位程序中有没有可能发生某些异常</p>
<p>但是我们使用了 <code>except</code> ，目前来说，我们就看不到异常是啥了。</p>
<p>这个时候，python的标准库 <code>traceback</code> 就排上用场了。</p>
<p><code>traceback</code>会记录所有异常信息到程序内部，等待你调用它的时候才会给你输出</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><code class="hljs python"><span class="hljs-keyword">import</span> traceback<br><br><span class="hljs-keyword">try</span>:<br>    <span class="hljs-built_in">int</span>(<span class="hljs-string">&#x27;a&#x27;</span>)<br><span class="hljs-keyword">except</span>:<br>    traceback.print_exc()    <span class="hljs-comment"># 打印异常信息, 直接输出到控制台</span><br>    error = traceback.format_exc()    <span class="hljs-comment"># 返回异常信息，可以用一个变量接住它，或者直接使用</span><br>    <span class="hljs-built_in">print</span>(<span class="hljs-string">&quot;代码异常信息：\n&quot;</span>,error)<br></code></pre></td></tr></table></figure>

<h2 id="主动抛出异常"><a href="#主动抛出异常" class="headerlink" title="主动抛出异常"></a>主动抛出异常</h2><p><strong>异常都是主动抛出的</strong></p>
<p>怎么理解这句话呢？我们分为两点：</p>
<ul>
<li>python自带的异常</li>
<li>使用标准库/第三方库/自己封装的代码，抛出的异常</li>
</ul>
<p><strong>先看第一点</strong></p>
<p>我们知道 <code>int(&#39;a&#39;)</code> 会抛出异常，但这个异常是 <strong>python主动抛出的</strong></p>
<p>它检测到这个参数，并不符合转化条件，于是会在转化前抛出异常给代码编写者。</p>
<p><strong>再看第二点</strong></p>
<p>我们这里封装一个函数，来模拟 <strong>主动抛出异常的场景</strong></p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br></pre></td><td class="code"><pre><code class="hljs python">dataDict = &#123;<br>    <span class="hljs-string">&#x27;name&#x27;</span>: <span class="hljs-string">&#x27;木舟&#x27;</span>,<br>    <span class="hljs-string">&#x27;age&#x27;</span>: <span class="hljs-number">18</span><br>&#125;<br><br><span class="hljs-keyword">def</span> <span class="hljs-title function_">maybyKeyError</span>(<span class="hljs-params">key</span>):<br>    <span class="hljs-keyword">if</span> key <span class="hljs-keyword">in</span> dataDict.keys():<br>        <span class="hljs-keyword">return</span> dataDict[key]<br>    <span class="hljs-keyword">else</span>:<br>        <span class="hljs-keyword">raise</span> KeyError(<span class="hljs-string">f&quot;你指定的key <span class="hljs-subst">&#123;key&#125;</span> 并不存在于字典中，请检查&quot;</span>)<br><br><span class="hljs-built_in">print</span>(<span class="hljs-string">&quot;first execute&quot;</span>)<br><span class="hljs-built_in">print</span>(maybyKeyError(<span class="hljs-string">&#x27;name&#x27;</span>))<br><br><span class="hljs-built_in">print</span>(<span class="hljs-string">&quot;\nsecond execute&quot;</span>)<br><span class="hljs-built_in">print</span>(maybyKeyError(<span class="hljs-string">&#x27;age&#x27;</span>))<br><br><span class="hljs-built_in">print</span>(<span class="hljs-string">&quot;\nthird execute&quot;</span>)<br><span class="hljs-built_in">print</span>(maybyKeyError(<span class="hljs-string">&#x27;sex&#x27;</span>))<br><br><span class="hljs-comment"># 结果</span><br><span class="hljs-string">&quot;&quot;&quot;</span><br><span class="hljs-string">first execute</span><br><span class="hljs-string">木舟</span><br><span class="hljs-string"></span><br><span class="hljs-string">second execute</span><br><span class="hljs-string">18</span><br><span class="hljs-string"></span><br><span class="hljs-string">third execute</span><br><span class="hljs-string">Traceback (most recent call last):</span><br><span class="hljs-string">  File &quot;C:\Users\86131\Desktop\python基础\test\test.py&quot;, line 21, in &lt;module&gt;</span><br><span class="hljs-string">    print(maybyKeyError(&#x27;sex&#x27;))</span><br><span class="hljs-string">  File &quot;C:\Users\86131\Desktop\python基础\test\test.py&quot;, line 11, in maybyKeyError</span><br><span class="hljs-string">    raise KeyError(f&quot;你指定的key &#123;key&#125; 并不存在于字典中，请检查&quot;)</span><br><span class="hljs-string">KeyError: &#x27;你指定的key sex 并不存在于字典中，请检查&#x27;</span><br><span class="hljs-string">&quot;&quot;&quot;</span><br></code></pre></td></tr></table></figure>

<p>我们通过 <code>raise</code>  <strong>主动</strong> 的抛出了一个异常，并且给予一些异常信息</p>
<h1 id="文件处理"><a href="#文件处理" class="headerlink" title="文件处理"></a>文件处理</h1><p>写程序的过程中，难免会对文件进行读写操作</p>
<p>比如：</p>
<ul>
<li>读取配置文件</li>
<li>输出文档</li>
</ul>
<h2 id="打开一个文件"><a href="#打开一个文件" class="headerlink" title="打开一个文件"></a>打开一个文件</h2><p>我们可以使用python内置的关键字 <code>open</code></p>
<p>这个关键字接收 <strong>文件路径</strong> 用来打开具体的文件</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><code class="hljs python">f = <span class="hljs-built_in">open</span>(<span class="hljs-string">&#x27;./test.txt&#x27;</span>)<br>f.close()<br></code></pre></td></tr></table></figure>

<p>注意！用open打开的文件，需要在使用后关闭。目的是释放资源以及能够删除该文件。</p>
<h2 id="文件打开的模式"><a href="#文件打开的模式" class="headerlink" title="文件打开的模式"></a>文件打开的模式</h2><p>一般来说，我们打开一个文件都是带有目的的，比如说：读/写</p>
<p>所以根据不同的目的，也会有不同的模式。</p>
<p>一般常用的就是：</p>
<ul>
<li>r, 只读模式，无法写入, 文件指针在开头位置</li>
<li>w，写模式，打开文件时，会清空原有的内容, 文件指针在开头位置</li>
<li>a，追加模式，写入时，会在文件尾部进行内容添加。文件指针在结尾位置</li>
<li>r+, 读写模式, 文件指针在开头位置写入时，会覆盖原有的内容</li>
<li>w+, 读写模式, 文件指针在开头位置，打开文件时，会清空原有的内容</li>
<li>a+, 追加读写模式, 文件指针在尾部位置，写入时，会在文件尾部进行内容添加</li>
<li>rb+, 以二进制模式打开，其余的和上述一致</li>
<li>wb+, 以二进制模式打开，其余的和上述一致</li>
<li>ab+, 以二进制模式打开，其余的和上述一致</li>
</ul>
<h2 id="文件方法"><a href="#文件方法" class="headerlink" title="文件方法"></a>文件方法</h2><p>常用的：</p>
<ul>
<li>read，读取文件内容</li>
<li>write，写入文件内容，注意，参数必须是字符串</li>
<li>readline，按行读取内容，一行一行的读</li>
<li>tell，获取文件指针位置</li>
<li>seek，修改文件指针位置</li>
</ul>
<h2 id="文件路径"><a href="#文件路径" class="headerlink" title="文件路径"></a>文件路径</h2><p>打开文件需要传递路径，所以这个知识点也是不能避开的。</p>
<p>路径类型分为两种：</p>
<ul>
<li>相对路径，相对于运行路径</li>
<li>绝对路径，从盘符开始的路径</li>
</ul>
<p>一般来说，文件类型的操作，我都强烈推荐使用绝对路径</p>
<p>因为 <strong>相对路径太危险！</strong></p>
<p>注意，相对路径是 <strong>相对于运行路径</strong></p>
<p>也就是说，运行路径的不同，相对路径换算出来的路径也会不同。</p>
<p>比如，我们在根目录下新建一个文件夹 <code>test</code></p>
<p>在 <code>test</code> 文件夹下，新建一个 <code>test.py</code></p>
<p>test/test.py:</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><code class="hljs python"><span class="hljs-keyword">import</span> os<br><br><span class="hljs-comment"># 通过 os.path.abspath 来获取相对路径换算出来的绝对路径</span><br><span class="hljs-built_in">print</span>(os.path.abspath(<span class="hljs-string">&#x27;./text.txt&#x27;</span>))  <br></code></pre></td></tr></table></figure>

<p>然后，我们在cmd或者idea自带的 <strong>终端</strong> 中分别运行：</p>
<figure class="highlight sh"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><code class="hljs sh">python <span class="hljs-built_in">test</span>/test.py<br></code></pre></td></tr></table></figure>

<figure class="highlight sh"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><code class="hljs sh"><span class="hljs-built_in">cd</span> <span class="hljs-built_in">test</span><br>python test.py<br></code></pre></td></tr></table></figure>

<figure class="highlight sh"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><code class="hljs sh"><span class="hljs-comment"># 结果(以下结果为我电脑目录结果，实际上只需要注意最后的text.txt路径)：</span><br><span class="hljs-comment"># 1. C:\Users\xxx\Desktop\python基础\text.txt</span><br><span class="hljs-comment"># 2. C:\Users\xxx\Desktop\python基础\test\text.txt</span><br></code></pre></td></tr></table></figure>

<p>可以发现，同样的代码，不同的 <strong>运行环境</strong> 得出来的路径大不一样</p>
<p>所以我推荐，使用相对路径是，需要先获取出 <strong>当前文件位置父文件夹路径</strong> 再进行 <strong>相对路径拼接</strong></p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><code class="hljs python"><span class="hljs-keyword">import</span> os<br><br><span class="hljs-built_in">print</span>(<br>    os.path.abspath(<br>        os.path.join(  <span class="hljs-comment"># join是路径拼接</span><br>            os.path.dirname(__file__),  <span class="hljs-comment"># __file__ 指向的是当前文件路径，dirname获取的是父文件夹路径</span><br>            <span class="hljs-string">&#x27;./test.txt&#x27;</span><br>        )<br>    )<br>)<br></code></pre></td></tr></table></figure>

<p>这个时候再分别运行之前的命令，你会发现，结果都是一样的。</p>
<p>当然你可以封装成一个函数方便在 <strong>你的项目的任何位置调用</strong></p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><code class="hljs python"><span class="hljs-keyword">import</span> os<br><br><span class="hljs-keyword">def</span> <span class="hljs-title function_">getPath</span>(<span class="hljs-params">filePath, relativePath</span>):<br>    <span class="hljs-keyword">return</span> os.path.abspath(<br>            os.path.join( <br>                os.path.dirname(filePath),  <br>                relativePath<br>            )<br>    )<br><br><span class="hljs-built_in">print</span>(getPath(__file__, <span class="hljs-string">&#x27;./test.txt&#x27;</span>))<br></code></pre></td></tr></table></figure>

<h2 id="文件关闭的正确姿势"><a href="#文件关闭的正确姿势" class="headerlink" title="文件关闭的正确姿势"></a>文件关闭的正确姿势</h2><p>如我之前所说，文件打开后，一定要记得关闭。</p>
<p>但是有些时候，我们在操作文件的过程中，<strong>难免会遇到报错</strong></p>
<p>如果遇到报错，那么 <code>f.close</code> 也许就不会正常的运行，那么文件就会一直处于 <strong>打开状态</strong></p>
<p>这是一个十分可怕的事情！</p>
<p>那么我们可以用两种方式来处理这种情况：</p>
<p><strong>第一种</strong></p>
<p>还记得我们的 <code>try</code> 吗？</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><code class="hljs python">f = <span class="hljs-built_in">open</span>(<span class="hljs-string">&#x27;xxx&#x27;</span>)<br><span class="hljs-keyword">try</span>:<br>    <span class="hljs-comment"># 写你的代码</span><br>    ...<br><span class="hljs-keyword">finally</span>:<br>    f.close()<br></code></pre></td></tr></table></figure>

<p>这样就能保证不管如何，都会执行 <code>f.close</code></p>
<p><strong>第二种</strong></p>
<p>通过python的关键字 <code>with</code></p>
<p>这是一种更优雅的方式，也是面试高频问题</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><code class="hljs python"><span class="hljs-keyword">with</span> <span class="hljs-built_in">open</span>(<span class="hljs-string">&#x27;xxx&#x27;</span>) <span class="hljs-keyword">as</span> f:<br>    <span class="hljs-comment"># 写你的代码</span><br>    ...<br></code></pre></td></tr></table></figure>

<p>是的，通过这种方式，我们再也不需要手动的去执行 <code>f.close</code></p>
<p>也不用担心触发异常，<strong>因为 <code>with</code> 不管你是正常执行还是异常执行，都会正确的帮你关闭文件</strong></p>
<p>其中的原理，我想你需要看我博客的另一篇文章：</p>
<p><a href="https://walker_kwu.gitee.io/my-blog/2022/07/16/python/advanced/with/">https://walker_kwu.gitee.io/my-blog/2022/07/16/python/advanced/with/</a></p>

                
              </div>
            
            <hr/>
            <div>
              <div class="post-metas my-3">
  
    <div class="post-meta mr-3 d-flex align-items-center">
      <i class="iconfont icon-category"></i>
      

<span class="category-chains">
  
  
    
      <span class="category-chain">
        
  <a href="/my-blog/categories/python/" class="category-chain-item">python</a>
  
  
    <span>></span>
    
  <a href="/my-blog/categories/python/Python%E5%9F%BA%E7%A1%80/" class="category-chain-item">Python基础</a>
  
  

  

      </span>
    
  
</span>

    </div>
  
  
    <div class="post-meta">
      <i class="iconfont icon-tags"></i>
      
        <a href="/my-blog/tags/%E6%B5%8B%E8%AF%95%E5%BC%80%E5%8F%91/">#测试开发</a>
      
        <a href="/my-blog/tags/Python%E5%9F%BA%E7%A1%80/">#Python基础</a>
      
    </div>
  
</div>


              
  

  <div class="license-box my-3">
    <div class="license-title">
      <div>python异常处理及文件处理</div>
      <div>https://walker_kwu.gitee.io/my-blog/2023/03/18/python/base/python异常处理及文件处理/</div>
    </div>
    <div class="license-meta">
      
        <div class="license-meta-item">
          <div>作者</div>
          <div>木舟</div>
        </div>
      
      
        <div class="license-meta-item license-meta-date">
          <div>发布于</div>
          <div>2023年3月18日</div>
        </div>
      
      
        <div class="license-meta-item license-meta-date">
          <div>更新于</div>
          <div>2023年5月23日</div>
        </div>
      
      <div class="license-meta-item">
        <div>许可协议</div>
        <div>
          
            
            
              <a target="_blank" href="https://creativecommons.org/licenses/by-nc-sa/4.0/">
              <span class="hint--top hint--rounded" aria-label="BY - 署名">
                <i class="iconfont icon-by"></i>
              </span>
              </a>
            
              <a target="_blank" href="https://creativecommons.org/licenses/by-nc-sa/4.0/">
              <span class="hint--top hint--rounded" aria-label="NC - 非商业性使用">
                <i class="iconfont icon-nc"></i>
              </span>
              </a>
            
              <a target="_blank" href="https://creativecommons.org/licenses/by-nc-sa/4.0/">
              <span class="hint--top hint--rounded" aria-label="SA - 相同方式共享">
                <i class="iconfont icon-sa"></i>
              </span>
              </a>
            
          
        </div>
      </div>
    </div>
    <div class="license-icon iconfont"></div>
  </div>



              
                <div class="post-prevnext my-3">
                  <article class="post-prev col-6">
                    
                    
                      <a href="/my-blog/2023/03/19/python/base/python%E5%B8%B8%E7%94%A8%E6%A0%87%E5%87%86%E5%BA%93/" title="python常用标准库">
                        <i class="iconfont icon-arrowleft"></i>
                        <span class="hidden-mobile">python常用标准库</span>
                        <span class="visible-mobile">上一篇</span>
                      </a>
                    
                  </article>
                  <article class="post-next col-6">
                    
                    
                      <a href="/my-blog/2023/03/11/python/base/python%E9%9D%A2%E5%90%91%E5%AF%B9%E8%B1%A1%EF%BC%88%E4%B8%8B%EF%BC%89/" title="python面向对象（下）">
                        <span class="hidden-mobile">python面向对象（下）</span>
                        <span class="visible-mobile">下一篇</span>
                        <i class="iconfont icon-arrowright"></i>
                      </a>
                    
                  </article>
                </div>
              
            </div>

            
          </article>
        </div>
      </div>
    </div>

    <div class="side-col d-none d-lg-block col-lg-2">
      

    </div>
  </div>
</div>





  



  



  



  



  







    

    
      <a id="scroll-top-button" aria-label="TOP" href="#" role="button">
        <i class="iconfont icon-arrowup" aria-hidden="true"></i>
      </a>
    

    
      <div class="modal fade" id="modalSearch" tabindex="-1" role="dialog" aria-labelledby="ModalLabel"
     aria-hidden="true">
  <div class="modal-dialog modal-dialog-scrollable modal-lg" role="document">
    <div class="modal-content">
      <div class="modal-header text-center">
        <h4 class="modal-title w-100 font-weight-bold">搜索</h4>
        <button type="button" id="local-search-close" class="close" data-dismiss="modal" aria-label="Close">
          <span aria-hidden="true">&times;</span>
        </button>
      </div>
      <div class="modal-body mx-3">
        <div class="md-form mb-5">
          <input type="text" id="local-search-input" class="form-control validate">
          <label data-error="x" data-success="v" for="local-search-input">关键词</label>
        </div>
        <div class="list-group" id="local-search-result"></div>
      </div>
    </div>
  </div>
</div>

    

    
  </main>

  <footer>
    <div class="footer-inner">
  
    <div class="footer-content">
       <span>By 木舟</span> <i class="iconfont icon-love"></i> 
    </div>
  
  
    <div class="statistics">
  
  

  
    
      <span id="busuanzi_container_site_pv" style="display: none">
        总访问量 
        <span id="busuanzi_value_site_pv"></span>
         次
      </span>
    
    
      <span id="busuanzi_container_site_uv" style="display: none">
        总访客数 
        <span id="busuanzi_value_site_uv"></span>
         人
      </span>
    
    
  
</div>

  
  
  
</div>

  </footer>

  <!-- Scripts -->
  
  <script  src="https://lib.baomitu.com/nprogress/0.2.0/nprogress.min.js" ></script>
  <link  rel="stylesheet" href="https://lib.baomitu.com/nprogress/0.2.0/nprogress.min.css" />

  <script>
    NProgress.configure({"showSpinner":false,"trickleSpeed":100})
    NProgress.start()
    window.addEventListener('load', function() {
      NProgress.done();
    })
  </script>


<script  src="https://lib.baomitu.com/jquery/3.6.0/jquery.min.js" ></script>
<script  src="https://lib.baomitu.com/twitter-bootstrap/4.6.1/js/bootstrap.min.js" ></script>
<script  src="/my-blog/js/events.js" ></script>
<script  src="/my-blog/js/plugins.js" ></script>


  <script  src="https://lib.baomitu.com/typed.js/2.0.12/typed.min.js" ></script>
  <script>
    (function (window, document) {
      var typing = Fluid.plugins.typing;
      var subtitle = document.getElementById('subtitle');
      if (!subtitle || !typing) {
        return;
      }
      var text = subtitle.getAttribute('data-typed-text');
      
        typing(text);
      
    })(window, document);
  </script>




  
    <script  src="/my-blog/js/img-lazyload.js" ></script>
  




  
<script>
  Fluid.utils.createScript('https://lib.baomitu.com/tocbot/4.18.2/tocbot.min.js', function() {
    var toc = jQuery('#toc');
    if (toc.length === 0 || !window.tocbot) { return; }
    var boardCtn = jQuery('#board-ctn');
    var boardTop = boardCtn.offset().top;

    window.tocbot.init({
      tocSelector     : '#toc-body',
      contentSelector : '.markdown-body',
      headingSelector : CONFIG.toc.headingSelector || 'h1,h2,h3,h4,h5,h6',
      linkClass       : 'tocbot-link',
      activeLinkClass : 'tocbot-active-link',
      listClass       : 'tocbot-list',
      isCollapsedClass: 'tocbot-is-collapsed',
      collapsibleClass: 'tocbot-is-collapsible',
      collapseDepth   : CONFIG.toc.collapseDepth || 0,
      scrollSmooth    : true,
      headingsOffset  : -boardTop
    });
    if (toc.find('.toc-list-item').length > 0) {
      toc.css('visibility', 'visible');
    }
  });
</script>


  <script src=https://lib.baomitu.com/clipboard.js/2.0.10/clipboard.min.js></script>

  <script>Fluid.plugins.codeWidget();</script>


  
<script>
  Fluid.utils.createScript('https://lib.baomitu.com/anchor-js/4.3.1/anchor.min.js', function() {
    window.anchors.options = {
      placement: CONFIG.anchorjs.placement,
      visible  : CONFIG.anchorjs.visible
    };
    if (CONFIG.anchorjs.icon) {
      window.anchors.options.icon = CONFIG.anchorjs.icon;
    }
    var el = (CONFIG.anchorjs.element || 'h1,h2,h3,h4,h5,h6').split(',');
    var res = [];
    for (var item of el) {
      res.push('.markdown-body > ' + item.trim());
    }
    if (CONFIG.anchorjs.placement === 'left') {
      window.anchors.options.class = 'anchorjs-link-left';
    }
    window.anchors.add(res.join(', '));
  });
</script>


  
<script>
  Fluid.utils.createScript('https://lib.baomitu.com/fancybox/3.5.7/jquery.fancybox.min.js', function() {
    Fluid.plugins.fancyBox();
  });
</script>


  <script>Fluid.plugins.imageCaption();</script>

  <script  src="/my-blog/js/local-search.js" ></script>

  <script defer src="https://busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js" ></script>





<!-- 主题的启动项，将它保持在最底部 -->
<!-- the boot of the theme, keep it at the bottom -->
<script  src="/my-blog/js/boot.js" ></script>


  

  <noscript>
    <div class="noscript-warning">博客在允许 JavaScript 运行的环境下浏览效果更佳</div>
  </noscript>
</body>
</html>
